# -*- coding: utf-8 -*-
from tornado import gen
from common import timetool
from qcmodule import push
from settings import mysql_app_pool


@gen.coroutine
def get_push_info_notice(info_id):
    sql = (
        "select a.id as news_id, a.title,a.create_time as pubtime "
        "from app_news_info a where a.id = {}"
    )
    info = yield mysql_app_pool.get_one(sql.format(info_id), cursor='dict')
    sql_cnt = "select cnt from app_view_cnt where view_id = {}"
    view_cnt = yield mysql_app_pool.get_one(sql_cnt.format(info['news_id']), cursor='dict')
    info['view_cnt'] = view_cnt['cnt'] if view_cnt else 0
    raise gen.Return(info)


@gen.coroutine
def deal_push_notice():
    start_time = timetool.get_timestamp()
    sql = "select * from app_push_task where status = 0 and type=2 order by id limit 10"
    res = yield mysql_app_pool.get_all(sql, cursor='dict')
    if res:
        sql_1 = "update app_push_task set status = 1, start_time={} where type=2 and id BETWEEN {} and {};"
        yield mysql_app_pool.update(sql_1.format(start_time, res[0]['id'], res[-1]['id']))
        for item in res:
            push_info = yield get_push_info_notice(item['info_id'])
            if not push_info:
                continue
            push_info['push_type'] = item['type']
            print push_info
            info_dict = dict(
                content=push_info,
                title=u"收到一条系统消息",
                text=""
            )
            push_res = push.push_message_to_app(info_dict)
            end_time = timetool.get_timestamp()
            if push_res['result'] == 'ok':
                sql_2 = "update app_push_task set status = 2, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_2.format('success', end_time, item['id']))
            else:
                sql_3 = "update app_push_task set status = 3, push_status='{}',end_time={} where id = {};"
                yield mysql_app_pool.update(sql_3.format('fail', end_time, item['id']))
    else:
        print 'notice nothing to do....'

